/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * DBClient.java
 *
 * Created on May 4, 2012, 9:50:19 PM
 */
package db.client.GUI;

import db.client.BUS.QueryBUS;
import db.client.DTO.QueryDTO;

import java.awt.Dimension;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.swing.ImageIcon;
import javax.swing.JFileChooser;
import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;

/**
 *
 * @author QuangKhai
 */
public final class DBClient extends javax.swing.JFrame {    
    private JPopupMenu menuTabbedPane = new JPopupMenu("PopupTabbedPane");
    private QueryBUS queryBUS = new QueryBUS();    
    public static DBClientStart dbClientStart;
    public boolean isConnected = false;
    public List<String> databaseName = new ArrayList<String>();
    public Socket socket;
    public ObjectOutputStream oos;
    public ObjectInputStream ois;  
    public List<List<String>> lstColumns = new ArrayList<List<String>>();
    
    /** Creates new form DBClient */
    public DBClient() {
        initComponents();
        
        //Set Icon for JFrame
        ImageIcon icon = new ImageIcon(getClass().getResource("/image/ClientIcon.png"));
        this.setIconImage(icon.getImage());
        //checkLogin();
        try {
            Thread.sleep(5000);
            DBClient.dbClientStart.dispose();
        } catch (InterruptedException ex) {
            Logger.getLogger(DBClientStart.class.getName()).log(Level.SEVERE, null, ex);
        }
        
        showLogin();        
        bt_connect.setEnabled(true);
        
        this.setSize(this.getWidth(), this.getHeight());
        Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
        this.setLocation((d.width - this.getWidth()) / 2, (d.height - this.getHeight()) / 2);
    }

    public void getDatabase(List<String> database){
        this.databaseName = database;
    }
    public void setTab(){        
        tabpane.addMouseListener(new MouseAdapter() {
        @Override
            public void mouseReleased(MouseEvent e) {             
                if (e.isPopupTrigger()) {                    
                    menuTabbedPane.show(e.getComponent(), e.getX(), e.getY());
                }
            }
        });

        //Add a mouse listener - create context menu of Tab
        final String itemsDatabase[] = new String[]{"Close this tab", "Close all tab"};
        for (int i = 0; i < itemsDatabase.length; i++) {
            JMenuItem item = new JMenuItem(String.valueOf(itemsDatabase[i]));
            final String chosen = itemsDatabase[i];
            item.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {                    
                    if(chosen.compareTo("Close this tab") == 0){
                        tabpane.remove(tabpane.getSelectedIndex());
                    } else if(chosen.compareTo("Close all tab") == 0){
                        closeAllTab();
                    }
                }
            });

            menuTabbedPane.add(item);
        }
    }
    
    public void closeAllTab(){
        for(int i = 0; i < tabpane.getTabCount(); i++){
            tabpane.remove(i);
            i--;
        }
    }
    
    public void showNewQuery(){
        menuTabbedPane.removeAll();             
        tabpane.addTab("New Query", new DBClientQuery(tabpane, databaseName, socket, oos, ois, lstColumns)); 
        setTab();                  
    }
    
    public void showLogin(){
        menuTabbedPane.removeAll();             
        tabpane.addTab("Login", new DBClientLogin(tabpane, this, lb_status));  
        setEnable(false);
        setTab();                  
    }
    
    public void checkLogin(){
        if(isConnected){            
            setEnable(true);
        }
    }
    
    public void setEnable(boolean tf){        
        bt_disconnect.setEnabled(tf);
        bt_execute.setEnabled(tf);
        bt_newsql.setEnabled(tf);
        bt_open.setEnabled(tf);
        bt_save.setEnabled(tf);
        bt_saveall.setEnabled(tf);
        bt_connect.setEnabled(!tf);
    }
    
    public void openQueryFile(){
        menuTabbedPane.removeAll();
        QueryDTO query = new QueryDTO();

        JFileChooser fc = new JFileChooser();    
        int returnVal = fc.showOpenDialog(this);
        if (returnVal == JFileChooser.APPROVE_OPTION) {  
            String s = fc.getSelectedFile().toString();
            query = queryBUS.readQueryFile(s);

            DBClientQuery newQuery = new DBClientQuery(tabpane, databaseName, socket, oos, ois, query, lstColumns);
            tabpane.addTab("New Query", newQuery);  

            setTab();           
        }
    }
    
    public void save(int index){
        String tilte = tabpane.getTitleAt(index);
    
        if(tilte.compareTo("New Query") == 0){
            DBClientQuery newQuery = null;
            newQuery = (DBClientQuery)tabpane.getComponentAt(index);
            newQuery.save();
        }
    }
    
    public void saveAll(){
        for(int i = 0; i < tabpane.getTabCount(); i++){
            save(i);
        }
    }
    
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jToolBar1 = new javax.swing.JToolBar();
        bt_connect = new javax.swing.JButton();
        bt_disconnect = new javax.swing.JButton();
        jSeparator4 = new javax.swing.JToolBar.Separator();
        bt_newsql = new javax.swing.JButton();
        jSeparator1 = new javax.swing.JToolBar.Separator();
        bt_open = new javax.swing.JButton();
        bt_save = new javax.swing.JButton();
        bt_saveall = new javax.swing.JButton();
        jSeparator2 = new javax.swing.JToolBar.Separator();
        bt_execute = new javax.swing.JButton();
        jSeparator3 = new javax.swing.JToolBar.Separator();
        bt_about = new javax.swing.JButton();
        tabpane = new javax.swing.JTabbedPane();
        lb_status = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("DB-Client");

        jToolBar1.setRollover(true);
        jToolBar1.setEnabled(false);

        bt_connect.setIcon(new javax.swing.ImageIcon(getClass().getResource("/image/connect.png"))); // NOI18N
        bt_connect.setToolTipText("Connect");
        bt_connect.setFocusable(false);
        bt_connect.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        bt_connect.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        bt_connect.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bt_connectActionPerformed(evt);
            }
        });
        jToolBar1.add(bt_connect);

        bt_disconnect.setIcon(new javax.swing.ImageIcon(getClass().getResource("/image/disconnect.png"))); // NOI18N
        bt_disconnect.setToolTipText("Disconnect");
        bt_disconnect.setFocusable(false);
        bt_disconnect.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        bt_disconnect.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        bt_disconnect.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bt_disconnectActionPerformed(evt);
            }
        });
        jToolBar1.add(bt_disconnect);
        jToolBar1.add(jSeparator4);

        bt_newsql.setIcon(new javax.swing.ImageIcon(getClass().getResource("/image/query.png"))); // NOI18N
        bt_newsql.setToolTipText("New query");
        bt_newsql.setFocusable(false);
        bt_newsql.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        bt_newsql.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        bt_newsql.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bt_newsqlActionPerformed(evt);
            }
        });
        jToolBar1.add(bt_newsql);
        jToolBar1.add(jSeparator1);

        bt_open.setIcon(new javax.swing.ImageIcon(getClass().getResource("/image/open.png"))); // NOI18N
        bt_open.setToolTipText("Open query file");
        bt_open.setFocusable(false);
        bt_open.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        bt_open.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        bt_open.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bt_openActionPerformed(evt);
            }
        });
        jToolBar1.add(bt_open);

        bt_save.setIcon(new javax.swing.ImageIcon(getClass().getResource("/image/save.png"))); // NOI18N
        bt_save.setToolTipText("Save");
        bt_save.setFocusable(false);
        bt_save.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        bt_save.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        bt_save.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bt_saveActionPerformed(evt);
            }
        });
        jToolBar1.add(bt_save);

        bt_saveall.setIcon(new javax.swing.ImageIcon(getClass().getResource("/image/save-all.png"))); // NOI18N
        bt_saveall.setToolTipText("Save all");
        bt_saveall.setFocusable(false);
        bt_saveall.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        bt_saveall.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        bt_saveall.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bt_saveallActionPerformed(evt);
            }
        });
        jToolBar1.add(bt_saveall);
        jToolBar1.add(jSeparator2);

        bt_execute.setIcon(new javax.swing.ImageIcon(getClass().getResource("/image/start.png"))); // NOI18N
        bt_execute.setToolTipText("Execute");
        bt_execute.setFocusable(false);
        bt_execute.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        bt_execute.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        bt_execute.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bt_executeActionPerformed(evt);
            }
        });
        jToolBar1.add(bt_execute);
        jToolBar1.add(jSeparator3);

        bt_about.setIcon(new javax.swing.ImageIcon(getClass().getResource("/image/about.png"))); // NOI18N
        bt_about.setToolTipText("About");
        bt_about.setFocusable(false);
        bt_about.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        bt_about.setName(""); // NOI18N
        bt_about.setVerticalAlignment(javax.swing.SwingConstants.TOP);
        bt_about.setVerticalTextPosition(javax.swing.SwingConstants.TOP);
        bt_about.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bt_aboutActionPerformed(evt);
            }
        });
        jToolBar1.add(bt_about);

        lb_status.setText("Status");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(tabpane, javax.swing.GroupLayout.DEFAULT_SIZE, 553, Short.MAX_VALUE)
            .addGroup(layout.createSequentialGroup()
                .addGap(10, 10, 10)
                .addComponent(lb_status, javax.swing.GroupLayout.DEFAULT_SIZE, 543, Short.MAX_VALUE))
            .addComponent(jToolBar1, javax.swing.GroupLayout.DEFAULT_SIZE, 553, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jToolBar1, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(tabpane, javax.swing.GroupLayout.DEFAULT_SIZE, 339, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(lb_status, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

private void bt_newsqlActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bt_newsqlActionPerformed
// TODO add your handling code here:
    showNewQuery();
}//GEN-LAST:event_bt_newsqlActionPerformed

private void bt_connectActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bt_connectActionPerformed
// TODO add your handling code here:
    showLogin(); 
    
}//GEN-LAST:event_bt_connectActionPerformed

private void bt_openActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bt_openActionPerformed
// TODO add your handling code here:
    openQueryFile();
}//GEN-LAST:event_bt_openActionPerformed

private void bt_aboutActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bt_aboutActionPerformed
// TODO add your handling code here:
    DBClientProfile.main(null);
}//GEN-LAST:event_bt_aboutActionPerformed

private void bt_disconnectActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bt_disconnectActionPerformed
// TODO add your handling code here:
    bt_connect.setEnabled(true);
    showLogin();
    setEnable(false);    
}//GEN-LAST:event_bt_disconnectActionPerformed

private void bt_saveallActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bt_saveallActionPerformed
// TODO add your handling code here:
    saveAll();
}//GEN-LAST:event_bt_saveallActionPerformed

private void bt_executeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bt_executeActionPerformed
// TODO add your handling code here:
    DBClientQuery newQuery = null;
    newQuery = (DBClientQuery)tabpane.getSelectedComponent();
    newQuery.execute();
}//GEN-LAST:event_bt_executeActionPerformed

private void bt_saveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bt_saveActionPerformed
// TODO add your handling code here:
    save(tabpane.getSelectedIndex());
}//GEN-LAST:event_bt_saveActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(DBClient.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(DBClient.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(DBClient.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(DBClient.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new DBClient().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton bt_about;
    private javax.swing.JButton bt_connect;
    private javax.swing.JButton bt_disconnect;
    private javax.swing.JButton bt_execute;
    private javax.swing.JButton bt_newsql;
    private javax.swing.JButton bt_open;
    private javax.swing.JButton bt_save;
    private javax.swing.JButton bt_saveall;
    private javax.swing.JToolBar.Separator jSeparator1;
    private javax.swing.JToolBar.Separator jSeparator2;
    private javax.swing.JToolBar.Separator jSeparator3;
    private javax.swing.JToolBar.Separator jSeparator4;
    private javax.swing.JToolBar jToolBar1;
    private javax.swing.JLabel lb_status;
    private javax.swing.JTabbedPane tabpane;
    // End of variables declaration//GEN-END:variables
}
